package main

import (
	"bytes"
	"io/ioutil"
	"log"
	mrand "math/rand"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"
	"regexp"
	"strconv"
	"strings"
	"time"
)

var (
	proxyAddr = "0.0.0.0:2001"
	//nextProxy = "http://127.0.0.1:2002"
	nextProxy1 = "http://127.0.0.1:2003"
	nextProxy2 = "http://127.0.0.1:2004"
	transport = &http.Transport{
		DialContext: (&net.Dialer{
			Timeout:   30 * time.Second, //连接超时
			KeepAlive: 30 * time.Second, //长连接超时时间
		}).DialContext,
		MaxIdleConns:          100,              //最大空闲连接
		IdleConnTimeout:       90 * time.Second, //空闲超时时间
		TLSHandshakeTimeout:   10 * time.Second, //tls握手超时时间
		ExpectContinueTimeout: 1 * time.Second,  //100-continue 超时时间
	}
)
func singleJoiningSlash(a, b string) string {
	aslash := strings.HasSuffix(a, "/")
	bslash := strings.HasPrefix(b, "/")
	switch {
	case aslash && bslash:
		return a + b[1:]
	case !aslash && !bslash:
		return a + "/" + b
	}
	return a + b
}
// NewMultipleHostsReverseProxy ...
func NewMultipleHostsReverseProxy(targets []*url.URL) *httputil.ReverseProxy {
	director := func(req *http.Request) {
		// 1. 随机负载均衡
		index := mrand.Intn(len(targets))
		target := targets[index]
		targetQuery := target.RawQuery
		req.URL.Scheme = target.Scheme
		req.URL.Host = target.Host

		// 2. url地址重写
		re, _ := regexp.Compile("^/dir(.*)")
		req.URL.Path = re.ReplaceAllString(req.URL.Path, "$1")
		req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
		if targetQuery == "" || req.URL.RawQuery == "" {
			req.URL.RawQuery = targetQuery + req.URL.RawQuery
		} else {
			req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
		}
		if _, ok := req.Header["User-Agent"]; !ok {
			// explicitly disable User-Agent so it's not set to default value
			req.Header.Set("User-Agent", "")
		}
		// 3.只在第一代理设置此header头
		req.Header.Set("X-Real-IP", req.RemoteAddr)
	}
	//更改内容
	modifyFunc := func(resp *http.Response) error {
		if resp.StatusCode != 200 {
			oldPlayload, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				return err
			}
			newPlayload := []byte("StatusCode error: " + string(oldPlayload))
			resp.Body = ioutil.NopCloser(bytes.NewBuffer(newPlayload))
			resp.ContentLength = int64(len(newPlayload))
			resp.Header.Set("Content-Length", strconv.FormatInt(int64(len(newPlayload)), 10))
		}
		return nil
	}
	//错误回调: 关闭real_server时测试，错误回调
	errFunc := func(rw http.ResponseWriter, req *http.Request, err error) {
		http.Error(rw, "ErrorHandler error: "+err.Error(), 500)
	}
	return &httputil.ReverseProxy{
		Director:       director,
		Transport:      transport,
		ModifyResponse: modifyFunc,
		ErrorHandler:   errFunc,
	}
}
func main() {
	url1, err := url.Parse(nextProxy1)
	if err != nil {
		log.Println(err)
	}
	url2, err := url.Parse(nextProxy2)
	if err != nil {
		log.Println(err)
	}
	urls := []*url.URL{url1, url2}
	proxy := NewMultipleHostsReverseProxy(urls)
	log.Println("start server on ", proxyAddr)
	log.Fatal(http.ListenAndServe(proxyAddr, proxy))
}